import { PlusOutlined } from '@ant-design/icons';
import { Button, Input, InputRef, message, Tag } from 'antd';
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import '../../styles/metadata.scss';
import datasetService from '@/api/services/datasetService';

interface Props {
  collectionId: string | undefined;
  indexes: string[];
  addIndex: (text: string) => void;
  removeIndex: (text: string) => void;
}

const Indexes = ({ collectionId, indexes, addIndex, removeIndex }: Props) => {
  const [inputVisible, setInputVisible] = useState<boolean>(false);
  const [inputValue, setInputValue] = useState('');
  const inputRef = useRef<InputRef>(null);

  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);

  const handleClose = async (removedTag: string) => {
    const res = await removeTag(removedTag);
    if (res) {
      removeIndex(removedTag);
    }
  };

  const showInput = () => {
    setInputVisible(true);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = async () => {
    const res = await addTag(inputValue);
    if (res) {
      addIndex(inputValue);
      setInputVisible(false);
      setInputValue('');
    } else {
      setInputVisible(false);
    }
  };

  const addTag = async (text: string) => {
    if (!text) {
      // message.warning('索引不能为空');
      // inputRef.current?.focus();
      return false;
    }

    if (!collectionId) {
      return false;
    }
    try {
      await datasetService.addCollectionIndex({
        collection_id: collectionId,
        text: text,
      });
      message.success('添加索引成功');
      return true;
    } catch (error) {
      console.error(error);
      inputRef.current?.focus();
      return false;
    }
  };

  const removeTag = async (text: string) => {
    if (!collectionId) {
      return;
    }
    try {
      await datasetService.delCollectionIndex({
        collection_id: collectionId,
        text: text,
      });
      message.success('删除索引成功');
      return true;
    } catch (error) {
      console.error(error);
      return false;
    }
  };

  const indexTag = useMemo(() => {
    return indexes.map((tag) => (
      <Tag
        key={tag}
        className="metadata-tag max-w-[300px] cursor-pointer truncate"
        closable
        onClose={(e) => {
          e.preventDefault();
          handleClose(tag);
        }}
      >
        {tag}
      </Tag>
    ));
  }, [indexes]);

  return (
    <>
      <div className="metadata mb-2 flex flex-wrap gap-1">{indexTag}</div>
      {inputVisible && (
        <Input
          className="metadata-input w-auto"
          ref={inputRef}
          type="text"
          // size="small"
          placeholder="[ENTER]或点击输入框外添加索引"
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
        />
      )}
      {!inputVisible && (
        <div style={{ width: "100%" }}>
          <Button style={{ width: "100%", border: "1px solid #1B6DFA" }} icon={<PlusOutlined />} onClick={showInput} type="text">
            新建索引
          </Button>


        </div>

      )}
    </>
  );
};

export default memo(Indexes);
